package com.example.warehouse.controller;

import com.example.warehouse.config.JWTUtil;
import com.example.warehouse.entity.User;
import com.example.warehouse.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    // 获取用户信息（根据用户名）
    @GetMapping("/{username}")
    public ResponseEntity<User> getUserByUsername(@PathVariable String username, @RequestHeader(value = "Authorization", required = false) String token) {
        // 如果提供了 Token，就进行验证
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);  // 去掉 "Bearer " 前缀
            if (JWTUtil.isTokenExpired(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);  // Token 过期
            }

            String usernameFromToken = JWTUtil.getUsernameFromToken(token);  // 获取 Token 中的用户名
            if (!username.equals(usernameFromToken)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null);  // 用户名不匹配
            }
        }

        // 查询用户信息
        User user = userService.getUserByUsername(username);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);  // 用户不存在
        }
        return ResponseEntity.ok(user);  // 返回用户信息
    }


    // 根据用户ID获取用户信息
    @GetMapping("/id/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        return ResponseEntity.ok(user);
    }

    // 用户登录接口
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody User user) {
        User foundUser = userService.getUserByUsername(user.getUsername());
        if (foundUser == null || !foundUser.getPassword().equals(user.getPassword())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
        }

        // 生成 JWT Token
        String token = JWTUtil.generateToken(foundUser.getUsername());
        return ResponseEntity.ok(token);  // 返回生成的 Token
    }



    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<String> registerUser(@RequestBody User user) {
        try {
            userService.createUser(user);
            return ResponseEntity.ok("用户注册成功");
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }

    // 更新用户信息
    @PutMapping("/{id}")
    public ResponseEntity<String> updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id); // 确保ID一致
        userService.updateUser(user);
        return ResponseEntity.ok("用户信息更新成功");
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.ok("用户删除成功");
    }

    // 检查用户名是否存在
    @GetMapping("/check/username/{username}")
    public ResponseEntity<Boolean> checkUsernameExist(@PathVariable String username) {
        return ResponseEntity.ok(userService.checkUsernameExist(username));
    }

    // 检查邮箱是否已注册
    @GetMapping("/check/email/{email}")
    public ResponseEntity<Boolean> checkEmailExist(@PathVariable String email) {
        return ResponseEntity.ok(userService.checkEmailExist(email));
    }
}
